/**
 * 
 */
package switchviz.graphic;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.media.opengl.GLCanvas;
import javax.swing.JFrame;

import switchviz.core.ResourceManager;

import com.sun.opengl.util.FPSAnimator;


/**
 * @author Thomas
 *
 */
public class GraphicsFrame extends JFrame
{
	private static final long serialVersionUID = 1L;
	
	private GLCanvas _canvas = null;
	private GraphicEventListener _eventListener = null;
	private FPSAnimator _animator = null;
	private int _renderrate = 60;
	
	public GraphicsFrame(GraphicEventListener eventListener)
	{
		super();
		this.setSize(1024, 768);
		initialize(eventListener);
		this.setIconImage(ResourceManager.getInstance().getImageIconView().getImage());
		startAnimator();
	}
	
	public GraphicsFrame(String title, int renderrate, GraphicEventListener eventListener)
	{
		super(title);
		this.setSize(1024, 768);
		initialize(eventListener);
		_renderrate = renderrate;
		this.setIconImage(ResourceManager.getInstance().getImageIconView().getImage());
		startAnimator();
	}
	
	public void resetAnimator(int renderrate)
	{
		_renderrate = renderrate;
		if (_animator != null && _animator.isAnimating())
			_animator.stop();
		if(_renderrate > 0)
			startAnimator();
	}
	
	private void startAnimator()
	{
		_animator = new FPSAnimator(getCanvas(), _renderrate);
		this.addWindowListener(new WindowAdapter() 
		{
	        public void windowClosing(WindowEvent e) 
	        {
		          new Thread(new Runnable() 
		          {
		              public void run() 
		              {
		            	  if(_animator.isAnimating())
		            	  {
		            		  _animator.stop();
		            	  }
		              }
		          }).start();
		    }
		});
		_animator.start();
	}
	
	public void stopAnimator()
	{
		new Thread(new Runnable() 
        {
            public void run() 
            {
          	  if(_animator.isAnimating())
          	  {
          		  _animator.stop();
          	  }
            }
        }).start();
	}
	
	private void initialize(GraphicEventListener eventListener)
	{
		setEventListener(eventListener);
		add(getCanvas());	
	}
	
	private GLCanvas getCanvas()
	{
		if (_canvas == null)
		{
			_canvas = new GLCanvas();
			_canvas.addGLEventListener(getEventListener());
			_canvas.addMouseListener(getEventListener());
			_canvas.addMouseMotionListener(getEventListener());
			_canvas.addKeyListener(getEventListener());
			_canvas.addMouseWheelListener(getEventListener());
		}
		
		return _canvas;
	}
	
	private void setEventListener(GraphicEventListener eventListener)
	{
		_eventListener = eventListener;
	}
	
	private GraphicEventListener getEventListener()
	{
		return _eventListener;
	}
}
